﻿using System.Collections.Generic;
using System.Linq;
using MvvmTest.Models;

namespace MvvmTest.Db;

public class LocalDb
{
    private List<Student> studentsList;
    
    public LocalDb()
    {
        init();
    }

    private void init()
    {
        studentsList = new List<Student>();
        for (int i = 0; i < 30; i++)
        {
            studentsList.Add(new Student()
            {
                Id = i,
                Name = $"Name {i}"
            });
        }
    }
    
    public List<Student> GetStudents()
    {
        return studentsList;
    }
    
    public void AddStudent(Student student)
    {
        studentsList.Add(student);
    }
    
    public void DeleteStudent(int id)
    {
        var model=studentsList.FirstOrDefault(x => x.Id == id);
        if (model != null)
        {
            studentsList.Remove(model);
        }
    }

    public List<Student> GetStudentsByName(string name)
    {
        return studentsList.Where(q => q.Name.Contains(name)).ToList();
    }
    
    public Student GetStudentById(int id)
    {
        var model = studentsList.FirstOrDefault(x => x.Id == id);
        if (model != null)
        {
            // 这里new是因为直接传递的话会有一个引用关系
            return new Student()
            {
                Id = model.Id,
                Name = model.Name
            };
        }
        return null;
    }
}